package arithmetic.thread;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author jiangfeng on 2022/1/22
 */
public class ThreadLocal1 {

    public static void main(String[] args){
        ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 4, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2000));
        ThreadLocal<Set<String>> threadLocal = new ThreadLocal<>();
        ThreadLocal<String> threadLocal2 = new ThreadLocal<>();
        for (int i = 0; i < 20; i++) {
            int finalI = i;
            executor.execute(()->{
                String name = Thread.currentThread().getName();
                System.out.println(name);
                String value  = name+"#"+ finalI;
                Set<String> strings = threadLocal.get();
                String s = threadLocal2.get();
                if(strings==null){
                    strings = new HashSet<String>();
                    System.out.println(name+ "新new了 set");
                }
                strings.add(value);
                System.out.println(name+" 有元素:"+String.join(",",strings));



                if(s==null){
                    s = new String();
                    System.out.println(name+ "新new了 string");
                }
                s+= value+",";
                System.out.println("threadLocal2:"+s);

            });
            try {
                TimeUnit.MILLISECONDS.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executor.shutdown();
    }
}
